import React from 'react'
import { Link, withRouter } from 'react-router-dom'

import './index.scss';
import { inject, observer } from 'mobx-react';

import WinHelper from '../../utils/WinHelper'

import ImageLoader from '../../styles/ImageLoader'

import { Modal, Button, Drawer, Icon, Input, message } from 'antd';
import TextArea from 'antd/lib/input/TextArea';
import { ETIME } from 'constants';

const styles = {
    each_line: {
        backgroundColor: 'red'
    }
};

function showObj(obj) {
    var arr = Object.keys(obj).map((key) => {
        return <p key={key} >{key}:{obj[key]}</p>
    })
    return (
        arr
    )
}

@inject('baseStore')
@observer
class TopHeader extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            visible: false,
            drawer_visible: false,
            exitModelShow: false,
            socket_data_input: '',
            to_be_teacher_pwd: ''

        };

    }

    closeApp = () => {
        NativeApp.exitApp();
    }

    showExitModal = () => {
        this.setState({
            exitModelShow: true,
        });
    };

    exitConfirm = e => {
        this.closeApp();
    };

    closeExitModal = e => {
        this.setState({
            exitModelShow: false,
        });
    };

    showModal = () => {
        this.setState({
            visible: true,
        });
    };


    hideModal = () => {
        this.setState({
            visible: false,
        });
    };

    showDrawer = () => {
        this.setState({
            drawer_visible: true,
        });
    };


    hideDrawer = () => {
        this.setState({
            drawer_visible: false,
        });
    };


    scaleRender = () => {
        var w = 1920;
        var h = 1080;

        var rw = this.props.baseStore.myWin.inner_w;
        var rh = this.props.baseStore.myWin.inner_h;

        var scaleX = rw / w;
        var scaleY = rh / h;

        this.props.baseStore.myWin.scale_x = scaleX
        this.props.baseStore.myWin.scale_y = scaleY;

        this.props.baseStore.myWin.scale_rate = scaleX / scaleY;

        document.getElementById("app").style.transform = 'scale(' + scaleX + ', ' + scaleY + ')';

        //不用了要
        window["scaleX"] = scaleX;
        window["scaleY"] = scaleY;
        window["scale"] = {
            x: scaleX,
            y: scaleX,
            rate: scaleX / scaleY
        };

    }

    resizeHandler = () => {
        this.props.baseStore.myWin.inner_w = window.innerWidth;
        this.props.baseStore.myWin.inner_h = window.innerHeight;
    }

    componentDidMount() {

        var that = this;

        window.listenerNativeCodeMap = {

        };

        window.listenerNativeCode = function (code, func) {
            var arr = []; //window.listenerNativeCodeMap[code] || [];
            arr.push(func);

            window.listenerNativeCodeMap[code] = arr;
        }

        window.triggerNativeCode = function (code) {
            var arr = window.listenerNativeCodeMap[code] || [];
            arr.forEach(func => {
                func(code);
            });
        }

        window.listenerNativeCode('4', function (code) {
            if (that.props.baseStore.topHeader.backTo && that.props.baseStore.topHeader.backTo.length > 0) {
                that.props.history.push(that.props.baseStore.topHeader.backTo);
            }
        })

        // window.listenerNativeCode('25', function (code) {
        //     alert("缩小");
        // })


        window.android2Code = function (code) {
            window.triggerNativeCode("" + code);
        }


        window.addEventListener('resize', function () {
            that.resizeHandler()
            that.scaleRender();
        });


        screen.orientation.addEventListener("change", function () {
            that.resizeHandler();
            that.scaleRender();
        }, false);

        that.resizeHandler();
        that.scaleRender();

        var count = 1;
        var ID = setInterval(() => {
            that.scaleRender();
            count++;
            if (false && count > 3) {
                clearInterval(ID);
            }
        }, 300);

        // if (window.innerWidth < window.screen.width || window.innerHeight < window.screen.height) {
        //     this.showModal();
        // } else {
        //     this.hideModal();
        // }


        this.socketDo();




    }

    socketDo() {
        var that = this;
        //连接服务端，因为本机使用localhost 所以connect(url)中url可以不填或写 http://localhost
        //var socket = io.connect('http://localhost:8888');
        var socket = io.connect('http://47.103.36.143:8888');
        this.props.baseStore.socketData.socket = socket;

        socket.on('connect', function (data) {
            console.log("连接成功")
        });

        socket.on("register_server_to_app", function (data) {
            console.log(data, "======register_server_to_app=====");
            that.props.baseStore.socketData = {
                ...that.props.baseStore.socketData,
                socket_success: true,
                header: data.header
            }
        });

        window.addEventListener('beforeunload', function () {
            socket.disconnect();
        }, false);




        // 监听 receiveMsg 事件，用来接收其他客户端推送的消息
        socket.on("teach_server_to_app", function (data) {
            // that.setState({
            //     "socket_data_input": JSON.stringify(data)
            // })
            console.log(JSON.stringify(data), "=======teach_server_to_app=======");


            if (data.body['type'] == "page_change") {
                //var page_change = data.body.content;
                that.props.history.push(data.body.content || "/");
            } else if (data.body['type'] == "notice_success") {
                message.success(data.body.content);
            } else if (data.body['type'] == "notice_error") {
                message.error(data.body.content);
            } else if (data.body['type'] == "to_be_teacher_success") {

                var teach_guid = data.body.content;
                that.props.baseStore.socketData.tearch_guid = teach_guid;

                if (teach_guid == that.props.baseStore.socketData.header.guid) {
                    that.props.baseStore.socketData.role = "1";
                    message.success("申请主控成功");
                    var data = {
                        header: that.props.baseStore.socketData.header,
                        body: {
                            type: "page_change",
                            content: 0
                        }
                    };
                    //给服务端发送 sendMsg事件名的消息
                    socket.emit("teach_app_to_server", data);
                } else {
                    that.props.baseStore.socketData.role = "0";

                    message.info("您已被控");
                }
            } else if (data.body['type'] == "release_teacher") {
                that.props.baseStore.socketData.role = "";
                message.info("控制解除");
            } else if (data.body['type'] == "do_action") {

                if (that.props.baseStore.socketData.role != "1") {
                    var { action, param } = data.body['content'];
                    that.props.baseStore.socketData.currentReactView[action](...param)

                }


            }

        });


    }

    componentWillUnmount = () => {
        this.setState = (state, callback) => {
            return;
        };
    }

    handlerInputChange = (e) => {

        this.setState({
            "socket_data_input": e.target.value
        })


        // var data = {
        //     client: "天巧星-燕青",
        //     msg: sendMsg.value
        // };
        // //给服务端发送 sendMsg事件名的消息
        // socket.emit("sendMsg", data);
    }


    render() {
        return (
            <div style={{ height: this.props.baseStore.topHeader.show ? '60px' : '0px' }} className="TopHeader">
                <div className="top_header_left">
                    {
                        this.props.baseStore.topHeader.backTo && <Link className="back_btn" to={this.props.baseStore.topHeader.backTo}>
                        </Link>
                    }
                    {
                        this.props.baseStore.topHeader.backHome && <Link className="home_btn" to="/entry">
                        </Link>
                    }
                </div>
                <div className="top_header_mid">

                    {this.props.baseStore.topHeader.title}

                    {/* <Link to="/login">此处只为测试</Link>
                    <Link to="/login">登陆页</Link>
                    <Link to="/entry">主页</Link>
                    <Link to="/courseList">课程临摹列表</Link>
                    <Link to="/showCourse">临摹页</Link> */}
                </div>

                <div className="top_header_right">
                    {/* <a onClick={() => this.launchFullScreen()} >全屏</a>
                    <a onClick={() => this.exitFullscreen()} >退出全屏</a> */}
                    <a onClick={() => this.showDrawer()} >调试辅助</a>
                    {/* <a onClick={() => this.showExitModal()} >关闭</a> */}
                    {/* <Icon type="logout" style={{ fontSize: '30px', color: 'white' }} onClick={this.showExitModal} /> */}

                    <Icon type="logout" style={{ fontSize: '30px', color: 'white' }} onClick={this.showExitModal} />
                    {/* <Link to="/login">登陆页</Link> */}
                    {/* <a id="close"  >关闭</a> */}
                </div>

                <Drawer
                    title="调试辅助"
                    placement="right"
                    closable={true}
                    onClose={this.hideDrawer}
                    visible={this.state.drawer_visible}
                    width={500}
                >
                    {
                        showObj(this.props.baseStore.myWin)
                    }

                    <Button>发送切换页面命令</Button>
                    <TextArea className="socket_data_input" name="socket_data_input" value={this.state.socket_data_input} onChange={this.handlerInputChange} style={{ marginTop: '10px' }} />
                </Drawer>

                <Modal
                    title="提示"
                    visible={this.state.visible}
                    onOk={this.launchFullScreen}
                    onCancel={this.hideModal}
                    okText="进入全屏"
                    cancelText="取消"
                >
                    <div>全屏会有更好的视觉体验</div>
                </Modal>

                <Modal
                    title="提示"
                    visible={this.state.exitModelShow}
                    onOk={this.exitConfirm}
                    onCancel={this.closeExitModal}
                    okText="确认"
                    cancelText="取消"
                >
                    确定退出?
                </Modal>


                {
                    this.props.baseStore.socketData.role == '' && <div className="remote_socket" onClick={this.applyTeachRole} >
                        申请主控
                    </div>
                }

                {
                    this.props.baseStore.socketData.role == '0' && <div className="remote_socket"  >
                        受控中
                    </div>
                }

                {
                    this.props.baseStore.socketData.role == '1' && <div className="remote_socket" onClick={this.releaseTeachRole} >
                        主控中
                    </div>
                }



                <Modal
                    title="申请主控"
                    visible={this.state.applyTeachRoleVisible}
                    onOk={this.applyTeachRoleOk}
                    onCancel={this.applyTeachRoleCancel}
                    okText={'确定'}
                    cancelText={'取消'}
                >
                    <Input.Password placeholder="请输入密码" value={this.state.to_be_teacher_pwd} onPressEnter={this.applyTeachRoleOk} onChange={this.applyTeachRoleInputChange} />
                </Modal>


                {
                    this.props.baseStore.socketData.role == "0" && <div className="lock_mask"></div>
                }

            </div >
        )
    }

    applyTeachRole = () => {
        this.setState({
            applyTeachRoleVisible: true,
            to_be_teacher_pwd: ''
        });
    }

    releaseTeachRole = () => {
        //给服务端发送 sendMsg事件名的消息
        this.props.baseStore.socketData.socket.emit("release_teacher", {
            header: this.props.baseStore.socketData.header,
            body: {

            }
        });
    }

    applyTeachRoleOk = () => {


        var that = this;

        //给服务端发送 sendMsg事件名的消息
        this.props.baseStore.socketData.socket.emit("apply_to_teacher", {
            header: that.props.baseStore.socketData.header,
            body: {
                content: this.state.to_be_teacher_pwd
            }
        });


        this.setState({
            applyTeachRoleVisible: false,
            to_be_teacher_pwd: ''
        });


    }

    applyTeachRoleCancel = () => {

        this.setState({
            applyTeachRoleVisible: false,
            to_be_teacher_pwd: ''
        });

    }

    applyTeachRoleInputChange = (e) => {
        this.setState({
            to_be_teacher_pwd: e.target.value
        });
    }


    launchFullScreen = () => {
        this.hideModal();
        WinHelper.launchFullscreen(document.documentElement);
    }

    exitFullscreen() {
        WinHelper.exitFullscreen();
    }



}

export default withRouter(TopHeader);